package com.whisperly.echotalk.other;

import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.LocaleList;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.whisperly.echotalk.bllmodel.BaseResponse;
import com.whisperly.echotalk.bllmodel.ResultBody;
import com.whisperly.echotalk.bllmodel.UserQuery;
import com.whisperly.echotalk.bllmodel.UserWithChat;
import com.whisperly.echotalk.starryb.R;
import com.whisperly.echotalk.starryb.netWorkUtils.BlinkCallback;
import com.whisperly.echotalk.starryb.netWorkUtils.NetworkUtils;
import com.whisperly.echotalk.starryb.utils.AppsManager;
import com.whisperly.echotalk.starryb.utils.GlobalData;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;

public class Records extends AppCompatActivity {
    private ListView dateListView;
    private ArrayAdapter<String> dateAdapter;

    private Button btn_back;
    private String userId;
    @Override
    protected void attachBaseContext(Context newBase) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newBase);
        String languageCode = prefs.getString("language", "en");
        super.attachBaseContext(updateResources(newBase, languageCode));
    }

    public Context updateResources(Context context, String languageCode) {
        Locale locale = new Locale(languageCode);
        Locale.setDefault(locale);

        Resources res = context.getResources();
        Configuration config = new Configuration(res.getConfiguration());
        config.setLocale(locale);
        LocaleList localeList = new LocaleList(locale);
        LocaleList.setDefault(localeList);
        config.setLocales(localeList);
        context = context.createConfigurationContext(config);
        return context;
    }
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.records);

        AppsManager.addActivity(this);

        dateListView = findViewById(R.id.date_list_view);
        btn_back = findViewById(R.id.btn_back);
        btn_back.setOnClickListener(v -> Records.super.onBackPressed());
        userId = getCurrentUserId();

        Log.e("userId",userId);

        loadDates();
    }

    private void loadDates() {
        Set<String> uniqueDates = new HashSet<>();

        UserQuery userQuery = new UserQuery();
        userQuery.setUserId(userId);
        NetworkUtils.loadDates(userQuery, new BlinkCallback() {
            @Override
            public void onSuccess(ResultBody<?> response) {
                if (response.getCode() == 200){
                    BaseResponse<?> data = (BaseResponse<?>)response.getData();
                    if (data != null && data.getData() != null){
                        List<?> data1 = (List<?>)data.getData();
                        for (Object object : data1) {
                            UserQuery userQuery = (UserQuery)object;
                            uniqueDates.add(userQuery.getDate());
                        }
                        List<String> dates = new ArrayList<>(uniqueDates); // 将Set转换为List
                        Collections.sort(dates);

                        dateAdapter = new ArrayAdapter<>(Records.this, android.R.layout.simple_list_item_1, dates);
                        dateListView.setAdapter(dateAdapter);
                        dateListView.setOnItemClickListener((parent, view, position, id) -> {
                            String selectedDate = dates.get(position);
                            showQueriesForDate(selectedDate);
                        });

                        return;
                    }
                }
                Log.e("loadDates","error");
            }

            @Override
            public void onFailure(Throwable throwable) {
                throw new RuntimeException(throwable);
            }
        });
    }

    private void showQueriesForDate(String date) {
        List<String> queriesDates = new ArrayList<>();;
        Log.e("data",date);
        UserQuery userQuery = new UserQuery();
        userQuery.setDate(date);
        userQuery.setUserId(userId);
        NetworkUtils.loadDatesByDate(userQuery, new BlinkCallback() {
            @Override
            public void onSuccess(ResultBody<?> response) {
                if (response.getCode() == 200){
                    BaseResponse<?> data = (BaseResponse<?>)response.getData();
                    if (data != null && data.getData() != null){
                        List<?> data1 = (List<?>)data.getData();
                        for (Object object : data1) {
                            UserQuery userQuery = (UserQuery)object;
                            queriesDates.add(userQuery.getQueries());
                        }
                    }
                    AlertDialog.Builder builder = new AlertDialog.Builder(Records.this);
                    Log.e("date11111111",queriesDates.toString());
                    builder.setTitle(getString(R.string.Questions_on) + ":" + date)
                            .setItems(queriesDates.toArray(new String[0]), null)
                            .setPositiveButton(R.string.OK, null).setCancelable(false)
                            .show();
                    return;
                }
                Log.e("showQueriesForDate","error");
            }

            @Override
            public void onFailure(Throwable throwable) {
                throw new RuntimeException(throwable);
            }
        });
    }

    private String getCurrentUserId() {
        return GlobalData.getUser().getObjectId();
    }
}
